// common/components/dicSelectTag/dicSelectTag.js

Component({
  externalClasses: ['hyy-class'],
  /**
   * 组件的属性列表
   */
  properties: {
    dicKey: {
      type: String,
      value: ''
    },

    // 是否多选
    multiple: {
      type: Boolean,
      value: false
    },
    // 回显值
    value: {
      type: null,
      value: null
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    // 缓存数据
    cacheData: [],
    dicList: [],
    val: null,
  },
  lifetimes: {

    ready() {
      wx.nextTick(() => {
        const find = getApp().globalData.dicList.find(item => item.type === this.data.dicKey)
        this.setData({
          dicList: find?.data || [],
          cacheData: this.data.value
        })
      })

    },
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onTag: function (e) {
      let cacheData = this.data.cacheData
      const val = e.currentTarget.dataset.item.dictValue
      const index = wx.$_.indexOf(cacheData, val)
      // 多选
      if (this.data.multiple) {
        if (index === -1) {
          cacheData.push(val)
        } else {
          cacheData.splice(index, 1)
        }
        this.setData({
          cacheData: cacheData,
          val: cacheData
        })
        this.triggerEvent('onTag', {
          value: cacheData
        })
      } else {
        // 单选
        this.setData({
          val: val
        })
        this.triggerEvent('onTag', {
          value: val
        })
      }


    }
  }
})